<template>
  <div>
    <div>
      <Row :gutter="16">
        <div class="cardDiv">
          <card class="card" icon="ios-options">
            <p slot="title" style="cursor: pointer" @click="ClickTitle">
              <Icon type="md-reorder"></Icon>
              {{firstdata.title}}
            </p>
            <CellGroup>
              <Tree :data="datalist" :load-data="loadData" @on-select-change="clickTree"></Tree>
            </CellGroup>
          </card>
        </div>
        <div class="search1">
          <Input class="search_input" v-model="searchText" placeholder="请输入住户名"/>
          <button class="search_btn" style="background-color: #235CA7;border-color: #235CA7" @click="getUserinfoByName">搜索</button>
        </div>
        <div :style="{height:offsetheight+'px'}">
          <el-amap vid="amap" class="amap-demo" :zoom="zoom" :center="center" :events="events">
            <!--中心标记点-->
            <el-amap-marker vid="index_center" :position="center" :offset="markerOffset" :events="events1">
              <div v-if="imgshow">
                <img :src="markerImg"/>
              </div>
              <div v-if="!imgshow">
                <img width="30" height="30" :src="markerImg1"/>
              </div>
            </el-amap-marker>
            <div v-if="BuildingShow">
              <el-amap-marker  v-for="(item,aindex) in BuildingList" :key="aindex"  vid="index_center" :position="item" :offset="markerOffset1" :events="buildingEvents">
                <div>
                  <img width="30" height="30" :src="markerImg1"/>
                </div>
              </el-amap-marker>
            </div>
            <!-- 小组区域-->
            <el-amap-polygon v-for="(polygon, index2) in polygons" :key="index2" :vid="polygon" :events="dot.events"
                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                             :fillOpacity="polygon.fillOpacity"></el-amap-polygon>
            <!-- 信息窗体-->
            <el-amap-info-window :visible="window.visible" :events="window.events" :position="window.center">
<!--                      :events="window.events">-->
                <div v-if="GridShow===1" class="info-window">
                  <div><Tag color="blue">当前选中级别：{{this.pickInfo.name}}</Tag></div>
                  <Row>
                    <Col v-if="parseInt(this.pickInfo.grade)<3" span="8">
                      <div>当前级别区数量<h1>{{StatisticsInfo.areaNum}}</h1></div>
                    </Col>
                    <Col v-if="parseInt(this.pickInfo.grade)<4" span="8">
                      <div>当前级别街道数量<h1>{{StatisticsInfo.streetNum}}</h1></div>
                    </Col>
                    <Col v-if="parseInt(this.pickInfo.grade)<5" span="8">
                      <div>当前级别社区数量<h1>{{StatisticsInfo.communityNum}}</h1></div>
                    </Col>
                    <Col v-if="parseInt(this.pickInfo.grade)<6" span="8">
                      <div>当前级别网格数量<h1>{{StatisticsInfo.gardennum}}</h1></div>
                    </Col>
                    <Col v-if="parseInt(this.pickInfo.grade)<7" span="8">
                      <div>当前级别楼数量<h1>{{StatisticsInfo.buildingnum}}</h1></div>
                    </Col>
                    <Col span="8">
                      <div>当前级别人数<h1>{{StatisticsInfo.usernum}}</h1></div>
                    </Col>
                    <Col span="8">
                      <div>当前级别户数<h1>{{StatisticsInfo.doorplatenum}}</h1></div>
                    </Col>
                  </Row>
                  <div class="detail" @click="showDetail">查看详情</div>
                </div>
                <div v-if="GridShow===2" class="info-window">
<!--                <div><Tag color="blue">当前选中级别：{{this.pickInfo.name}}</Tag></div>-->
                <Row>
                  <Col span="8">
                    <div>当前网格楼数量<h1>{{GardenStatisticsInfo.buildingnum}}</h1></div>
                  </Col>
                  <Col span="8">
                    <div>当前网格人数<h1>{{GardenStatisticsInfo.usernum}}</h1></div>
                  </Col>
                  <Col span="8">
                    <div>当前网格户数<h1>{{GardenStatisticsInfo.doorplatenum}}</h1></div>
                  </Col>
                </Row>
                <div class="detail" @click="GardenShowDetail">查看详情</div>
              </div>
                <div v-if="GridShow===3" class="info-window">
                <Row>
                  <Col span="8">
                    <div>当前网格人数<h1>{{BuildingStatistics.usernum}}</h1></div>
                  </Col>
                  <Col span="8">
                    <div>当前网格户数<h1>{{BuildingStatistics.doorplatenum}}</h1></div>
                  </Col>
                </Row>
                <div class="detail" @click="BuildingShowDetail">查看详情</div>
              </div>
            </el-amap-info-window>
          </el-amap>
        </div>
      </Row>
    </div>
    <grid-person ref="gridPerson"></grid-person>
  </div>
</template>

<script>
import { getStatistics, findOfficeLevelList, findTreeList, findAllGridList, getGridByGardenId, getGardenByCoordinates, findGardenXJList, getBuildingByCoordinates } from '@/api/eventlist'
import GridPerson from './components/grid-person'

export default {
  name: 'index',
  components: { GridPerson },
  data () {
    let self = this
    return {
      pickPath: '', // 选中网格坐标
      BuildingPath: '',
      imgshow: true, // 地图点样式显示
      GridShow: 1, // 信息窗体显示
      BuildingShow: false, // 网格下楼标记点显示
      BuildingList: [],
      markerImg: './img/poi-marker-red.png',
      markerImg1: 'http://imgdl.tripln.top/webhdfs/v1/itemorder/985f1cad3f80498e9e34f66d16e7dc55/SQ1598594622493/其他保险、救助、赔偿等有关情况的证明20_8680779304.png?op=OPEN&namenoderpcaddress=hadoop01:9000&offset=0',
      StatisticsInfo: {}, // 信息窗体统计
      GardenStatisticsInfo: {}, // 信息窗体统计
      BuildingStatistics: {},
      markerOffset: [-25, -45], // 地图点偏移
      markerOffset1: [-15, -15],
      offsetheight: document.documentElement.clientHeight - 145,
      datalist: [], // 树形结构list
      center: [123.412581, 41.805853], // 中心点
      zoom: 9, // 缩放程度
      address: '',
      lng: 0,
      lat: 0,
      firstdata: [],
      pickInfo: [],
      searchText: '',
      polygons: [
        {
          bubble: true,
          fillOpacity: '0.2',
          fillColor: '#f77777',
          path: []
        }
      ],
      dot: {
        events: {
          click (e) {
            if (self.pickPath.grade !== '6') {
              let x = e.target.w.path
              let y = []
              x.forEach(item => {
                let data = [item.lng, item.lat]
                y.push(data)
              })
              if (y.length > 0) {
                self.pickPath = JSON.stringify(y)
                self.getGridByGardenId(JSON.stringify(y), 'statistics')
              }
              self.window.visible = true
              self.GridShow = 2
              self.window.center = [e.lnglat.lng, e.lnglat.lat]
            }
            // console.log(e.target.Ce.path)
            // console.log(e.target.Ce.vid.path)
            // console.log(e.target.w.path)
            // console.log(e.target.w.vid.path)
          }
        }
      },
      events: {
        click (e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      },
      resultData: [],
      events1: {
        // mouseover
        click () {
          self.window.center = self.center
          self.window.visible = true
        }
        // mouseout () {
        //   self.window.visible = false
        // }
      },
      window: {
        center: [0, 0],
        visible: false,
        events: {
          close () {
            self.window.visible = false
            self.GridShow = 1
          }
        }
      },
      buildingEvents: {
        click (e) {
          let x = e.target.Ce.position.lng + ',' + e.target.Ce.position.lat
          self.BuildingList.forEach(item => {
            let y = item[0] + ',' + item[1]
            if (x === y) {
              self.getBuildingByCoordinates(y)
              self.GridShow = 3
              self.window.visible = true
              self.window.center = [e.lnglat.lng, e.lnglat.lat]
            }
          })
        }
      }

    }
  },
  methods: {
    getGridByGardenId (e, e1) {
      // statistics
      // person
      let data = {
        csc_mapjson: e,
        type: e1
      }
      getGridByGardenId(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.GardenStatisticsInfo = ret.data.data
        } else {
          this.$Notice.error({
            title: '查询失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    getUserinfoByName () {
      let data = {
        user_name: this.searchText
      }
      this.$refs.gridPerson.init(data, 2)
    },
    showDetail () {
      this.$refs.gridPerson.init(this.pickInfo, 1)
    },
    GardenShowDetail () {
      let data = {
        csc_mapjson: this.pickPath
      }
      getGardenByCoordinates(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          this.$refs.gridPerson.init(result, 1)
        } else {
          this.$Notice.error({
            title: '查询失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    BuildingShowDetail () {
      let data = {
        csc_mapjson: this.BuildingPath
      }
      getBuildingByCoordinates(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          this.$refs.gridPerson.init(result, 1)
        } else {
          this.$Notice.error({
            title: '查询失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    init () {
      this.tree()
    },
    ClickTitle () {
      this.init()
      this.pickInfo = this.firstdata
      this.polygons = []
      this.BuildingList = []
      this.setCenter()
      this.autoZoom()
    },
    // 获取树形图
    tree () {
      // 调整缩放程度
      this.autoZoom()
      findOfficeLevelList().then(res => {
        if (res.data.errcode === 0) {
          let result = res.data.data
          this.datalist = result.children
          this.firstdata = result
          this.pickInfo = result
          if (result.grade === '5') {
            let data = {
              grade: result.grade,
              id: result.id
            }
            findTreeList(data).then(ret => {
              if (ret.data.errcode === 0) {
                let result = ret.data.data
                this.datalist = result
              } else {
                this.$Notice.error({
                  title: '获取树形结构失败',
                  desc: ret.data.errmsg
                })
              }
            })
          }
          this.setCenter()
          this.autoZoom()
        } else {
          this.$Notice.error({
            title: '获取树形结构失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 异步加载其他部分树形
    loadData (item, callback) {
      let data = {
        grade: item.grade,
        id: item.id
      }
      findTreeList(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          callback(result)
        } else {
          this.$Notice.error({
            title: '获取树形结构失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 初始化中心点
    setCenter () {
      if (this.pickInfo.csc_mapjson === '' || this.pickInfo.csc_mapjson === undefined || this.pickInfo.csc_mapjson === null) {
        this.$Notice.error({
          title: '中心点获取失败',
          desc: '该区域未添加中心点'
        })
        this.center = [123.412581, 41.805853]
      } else {
        let pickInfo_center = this.pickInfo.csc_mapjson
        let str = pickInfo_center.split(',')
        if (str.length !== 2) {
          this.$Notice.error({
            title: '中心点获取失败',
            desc: '中心点数据格式不正确，重新选择'
          })
        } else {
          if (this.pickInfo.grade === '7') {
            this.markerOffset = [-15, -15]
            this.imgshow = false
          } else {
            this.markerOffset = [-25, -45]
            this.imgshow = true
          }
          this.center = []
          this.center.push(str[0])
          this.center.push(str[1])
          this.lng = str[0]
          this.lat = str[1]
        }
      }
    },
    // 缩放程度
    autoZoom () {
      if (this.pickInfo.grade === '7') {
        this.zoom = 18 // 楼
      } else if (this.pickInfo.grade === '6') {
        this.zoom = 17 // 小区
      } else if (this.pickInfo.grade === '5') {
        this.zoom = 15 // 社区
      } else if (this.pickInfo.grade === '4') {
        this.zoom = 14 // 街道
      } else if (this.pickInfo.grade === '3') {
        this.zoom = 12 // 区
      } else if (this.pickInfo.grade === '8') {
        this.zoom = 18 // 单元
      } else {
        this.zoom = 9
      }
    },
    // 查询网格全部数据
    findAllGridList () {
      let data = {
        grade: this.pickInfo.grade,
        id: this.pickInfo.id
      }
      findAllGridList(data).then(ret => {
        if (ret.data.errcode === 0) {
          if (ret.data.data.length > 0) {
            let result = ret.data.data
            result.forEach(item => {
              this.dispose(item.csc_mapjson)
            })
          }
        } else {
          this.$Notice.error({
            title: '查询网格数据失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 点击节点
    clickTree (e1, e2) {
      this.window.visible = false
      this.pickInfo = e2
      if (this.pickInfo.grade === '2' || this.pickInfo.grade === '3' || this.pickInfo.grade === '4') {
        this.polygons = []
        this.BuildingShow = false
        this.BuildingList = []
        if (this.pickInfo.grade === '4') {
          this.findAllGridList()
        }
        this.setCenter()
      } else if (this.pickInfo.grade === '5') {
        this.polygons = []
        this.BuildingShow = false
        this.BuildingList = []
        this.findAllGridList()
        this.setCenter()
      } else if (this.pickInfo.grade === '6') {
        this.markerOffset = [-25, -45]
        this.imgshow = true
        this.polygons = []
        this.BuildingShow = false
        this.BuildingList = []
        this.dispose(this.pickInfo.csc_mapjson)
        let x = this.autoCenter(this.pickInfo.csc_mapjson)
        this.center = []
        this.center.push(x[0])
        this.center.push(x[1])
        this.findGardenXJList(this.pickInfo.id)
      } else if (this.pickInfo.grade === '7') {
        this.polygons = []
        this.BuildingShow = false
        this.BuildingList = []
        this.setCenter()
      } else if (this.pickInfo.grade === '8') {
        this.$Notice.error({
          title: '获取失败',
          desc: '该级别无法在地图展示！'
        })
      }
      this.autoZoom()
    },
    findGardenXJList (e) {
      let data = {
        id: e
      }
      findGardenXJList(data).then(ret => {
        this.BuildingList = []
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          result.forEach(item => {
            if (item.csc_mapjson !== undefined) {
              let center = [parseFloat(item.csc_mapjson.split(',')[0]), parseFloat(item.csc_mapjson.split(',')[1])]
              this.BuildingList.push(center)
            }
          })
          this.BuildingShow = true
        } else {
          this.$Notice.error({
            title: '查询失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 处理多边形
    dispose (e) {
      try {
        let data = {
          bubble: true,
          fillColor: '#f77777',
          fillOpacity: '0.2',
          path: JSON.parse(e)
        }
        this.polygons.push(data)
        // this.polygons[0].path.push()
      } catch (e) {
        this.$Notice.error({
          title: '获取失败',
          desc: '数据格式不正确，重新选择'
        })
      }
    },
    // 根据多边形自动取中心点
    autoCenter (map) {
      let path = JSON.parse(map)
      let total_lng = 0.0
      let total_lat = 0.0
      path.forEach(arr => {
        total_lng += arr[0]
        total_lat += arr[1]
      })
      let newlng = total_lng / path.length
      let newlat = total_lat / path.length
      let newCenter = [newlng, newlat]
      return newCenter
    },
    getStatistics () {
      let data = {}
      if (this.pickInfo.grade === '7') {
        data = {
          grade: this.pickInfo.grade,
          building_id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      } else if (this.pickInfo.grade === '6') {
        data = {
          grade: this.pickInfo.grade,
          garden_id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      } else if (this.pickInfo.grade === '5') {
        data = {
          grade: this.pickInfo.grade,
          community_id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      } else if (this.pickInfo.grade === '4') {
        data = {
          grade: this.pickInfo.grade,
          street_id: this.pickInfo.id,
          id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      } else if (this.pickInfo.grade === '3') {
        data = {
          grade: this.pickInfo.grade,
          area_id: this.pickInfo.id,
          id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      } else if (this.pickInfo.grade === '2') {
        data = {
          grade: this.pickInfo.grade,
          id: this.pickInfo.id
        }
        this.getStatisticsInfo(data)
      }
    },
    getStatisticsInfo (e) {
      getStatistics(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.StatisticsInfo = ret.data.data
        } else {
          this.$Notice.error({
            title: '查询失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    getBuildingByCoordinates (e) {
      let data = {
        csc_mapjson: e
      }
      this.BuildingPath = e
      getBuildingByCoordinates(data).then(ret => {
        if (ret.data.errcode === 0) {
          let x = ret.data.data
          let data = {
            grade: x.grade,
            building_id: x.id
          }
          this.BuildingStatistics = {}
          getStatistics(data).then(ret => {
            if (ret.data.errcode === 0) {
              this.BuildingStatistics = ret.data.data
            } else {
              this.$Notice.error({
                title: '查询失败！',
                desc: ret.data.errmsg
              })
            }
          })
        }
      })
    }
  },

  mounted () {
    this.init()
  },
  watch: {
    // 'window.visible': {
    //   deep: true,
    //   handler: function (newV, oldV) {
    //     if (newV) {
    //       this.getStatistics()
    //     }
    //   }
    // }
    center: {
      deep: true,
      handler: function (newV, oldV) {
        this.getStatistics()
      }
    }
  }
}
</script>

<style scoped>
  .cardDiv {
    width: 250px;
    position: absolute;
    top: 30px;
    left: 20px;
    z-index: 1000;
  }

  .card {
    background:rgba(255,255,255,0.93);
    height:500px;
    overflow: auto;
  }

  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: rgba(255,255,255,0.93);
  }

  ::-webkit-scrollbar-thumb {
    border-radius:5px;
    -webkit-box-shadow: inset 0 0 6px rgba(250, 250, 250, .3);
    background-color: rgba(220,220,220,0.93);
  }

  ::-webkit-scrollbar-corner {
    background-color: rgba(255,255,255,0.93);
  }

  .toolbar {
    text-align: center;
    margin-top: 10px;
  }

  .search1 {
    width: 200px;
    position: absolute;
    top: 30px;
    left: 300px;
    z-index: 1000;
  }

  .search_input {
    display: inline-block;
    width: 160px;
  }

  .search_input /deep/ input {
    border-top-right-radius: 0px !important;
    border-bottom-right-radius: 0px !important;
    background-color: rgba(255,255,255,0.93) !important;
  }

  .search_btn {
    display: inline-block;
    width: 40px;
    height: 32px;
    cursor: pointer;
    background-color: rgba(45,140,240,0.93);
    color: #fff;
    z-index: 1001;
    font-size: 12px;
    border: 1px solid transparent;
    transition: border 0.2s ease-in-out, background 0.2s ease-in-out, box-shadow 0.2s ease-in-out, -webkit-box-shadow 0.2s ease-in-out;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    vertical-align: middle;
    line-height: normal;
    position: absolute;
    left: 160px;
  }

  .search_btn:hover {
    background: #57a3f3 !important;
    border-color: #57a3f3 !important;
  }

  .search_btn:active {
    background: #2b85e4 !important;
    border-color: #2b85e4 !important;
  }

  .page_style {
    margin-top: 10px;
    position: relative;
  }
  .info-window {
    text-align: left;
    width: 400px;
    height: 250px;
    margin-left: 30px;
    background:rgba(255,255,255,0.9);
    border-radius: 4px;
    position: relative;
    overflow: hidden;
  }
  .detail{
    width: 100%;
    height: 24px;
    color: #fff;
    background-color: #1a73e8;
    position: absolute;
    bottom: 0;
    font-size: 12px;
    line-height: 24px;
    text-align: center;
    cursor: pointer;
  }
</style>
